<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../extjs_all/resources/css/ext-all.css"></link>
<script type="text/javascript" src="../../extjs_all/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../../extjs_all/ext-all.js"></script>
<script type="text/javascript" src="../../extjs_all/source/locale/ext-lang-zh_CN.js"></script>

<!-- script type="text/javascript" src="../myext/PersonListGridPanel.js"></script> -->
<script type="text/javascript">
var id ="11a,22a,33a,44a";
var c = "11a1";
	Ext.onReady(function(){
		Ext.QuickTips.init();	//初始化Ext.QuickTips，以使得tip提示可用
		Ext.form.Field.prototype.msgTarget='side';		//提示后面显示图片标记
		/**
		 * JS中，当有对象需要引用的时候，必须在引用之前就定义，否则的话，需要在constructor中初始化
		 */
		DataDictInfoFormPanel = Ext.extend(Ext.form.FormPanel,{
			constructor:function(){
				DataDictInfoFormPanel.superclass.constructor.call(this,{
					labelWidth:80,
					defaults:{anchor:'90%'},		//自动拉伸
					baseCls:'x-plain',			//强制设置窗体颜色
					defaultType:'textfield',
					bodyStyle:'padding:8px',
					items:[{
						xtype:'hidden',
						name:'id'
					},{
						fieldLabel:'字典名称',
						allowBlank:false,
						name:'dictName',
						maxLength:50
					},{
						fieldLabel:'排列顺序',
						xtype:'numberfield',
						
						name:'itemId'
					},{
						fieldLabel:'附加值1',
						name:'value1',
					},{
						fieldLabel:'附加值2',
						name:'value2',
					},{
// 						store:new Ext.data.SimpleStore({
// 							fields:['fontValue','fontName'],
// 							data:[['1','宋体'],['2','楷体'],['3','魏碑'],['4','黑体']]
// 						}),
						fieldLabel:'父节点',
						xtype:'combo',
						triggerAction:'all',
						//valueField:'parentId',
						displayField:'dictName',
						//mode:'local',
						name:'parentId',
						//hiddenName:"parentId",	//当数据为本地数据的时候,可以通过键值对来获得下拉框的值,远程暂时没有解决方案
						
// 						//远程调用,查询到数据库中的数据,然后显示
						store:rankData = new Ext.data.JsonStore({  
							root:'list',
				            proxy : new Ext.data.HttpProxy({  
		                        url : 'dictparent.action'  
		                    }),  
		                    fields:['dictName','parentId']
		        		}) 
					},{
						fieldLabel:'备注',
						name:'remark',
					//	vtype:'age'
					}]
				})
			},
			getValues:function(){
				//alert(Ext.util.JSON.encode(this.form.getValues()));
				if(this.getForm().isValid()){
					this.fireEvent("submit",this,this.form.getValues());
				}else{
					throw Error("表单验证未通过！");		//抛出异常，在调用getValues函数的地方捕获并提示
				}
				//alert(this.getForm().getValues());
				return new Ext.data.Record(this.getForm().getValues());
			},
			setValues:function(re){
				this.getForm().loadRecord(re);
			},
			reset:function(){
				this.getForm().reset();
			}
		});
		/**
		 * 弹出编辑窗口类，提供创建和修改使用
		 */
		 DataDictInfoWindow = Ext.extend(Ext.Window,{
			//将FormPanel放到Window中
			form:null,
			constructor:function(){
				this.form = new DataDictInfoFormPanel(),
				DataDictInfoWindow.superclass.constructor.call(this,{
					plain:true,			//通过背景颜色来渲染窗口颜色
					width:500,
					modal:true,			//只能操作当前窗口
					closeAction:'hide',
					items:this.form,
					buttons:[{
							text:'确定',
							handler:this.onsubmit,
							scope:this
						},{
							text:'取消',
							handler:this.oncanel,
							scope:this
						}]
				});
				this.addEvents("submit");
			},	
			close:function(){
				this.form.reset();
				this.hide();
			},
			onsubmit:function(){
				try{
					this.fireEvent("submit",this,this.form.getValues());
					//获得Form提交后的ID,如果为空,表示添加,否则为修改
 					var id = Ext.util.JSON.encode(this.form.getValues().data.id);
					Ext.Ajax.request({
						url:'savedata.action',
						params:{
							content:"["+Ext.util.JSON.encode(this.form.getValues().data)+"]"
						},
						//提交成功后,处理一些事务
						 success : function(response){
							//alert(response.responseText);
							var value = Ext.util.JSON.decode(response.responseText);
							var cc =new Ext.data.Record.create(['id','itemId','dictName','value1','value2','remark','parentId']);
							var cdata = new cc(value.dataDict);
							//将数据插入到第一行,并删除store最后一行
							var gridStore = Ext.getCmp('dataDictGrid').store;
							var c = id.replace('"','').replace('"','');		//去除不必要的符号
							if(""==c){
								if(gridStore.getCount() == 20){
									gridStore.insert(0,cdata);
									gridStore.remove(gridStore.getAt(gridStore.getCount()-1));
								}else{
									//gridStore.add(cdata);
									gridStore.insert(0,cdata);
								}
							}else{
								var selectRe = Ext.getCmp('dataDictGrid').getSelectionModel().getSelected();			//获得Grid选择的record
								var data = selectRe.data;
								//alert(Ext.util.JSON.encode(data));		//获得Record的数据，然后转换成JSON打印
								//遍历record.data,修改原record的值
								for(var i in data){
									selectRe.set(i,cdata.get(i));
								}
								selectRe.commit();
							}
						}  
					});
				}catch(err){
					Ext.Msg.alert('提示',err);
					return ;
				}
				this.close();
			},
			oncanel:function(){
				this.close();
			}
		}) ;

		/*********************************/
		//添加
		InsertDataDictInfoWindow = Ext.extend(DataDictInfoWindow,{
			title:'添加数据'
		});
		//修改
		UpdateDataDictInfoWindow = Ext.extend(DataDictInfoWindow,{
			title:'修改数据',
			load:function(re){
				this.form.setValues(re);
			}
		});
		/**
		 * 数据显示Grid
		 */
		UserDataDictGrid = Ext.extend(Ext.grid.GridPanel,{
			insertDataDict:new InsertDataDictInfoWindow(),
			updateDataDict:new UpdateDataDictInfoWindow(),
			constructor:function(){
				this['store']= new Ext.data.JsonStore({
					root:'list',
					totalProperty:'cnt',
					url:'finddatas.action',
				fields:[{
							name:'id', type: 'int'
						},{
							name:'itemId', type: 'int'
						},'dictName','value1','value2','remark','parentId']
				}),
				//ToolBar
				this['toolBar'] = new Ext.Toolbar({
					
					items:[{
						text:'新增',
						icon:'../imgs/add.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
						handler:function(){
							this.insertDataDict.show();
						},
						scope:this
					},"-",{
						text:'修改',
						icon:'../imgs/edit.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
						handler:function(){
							this.updateDataDict.show();						//首先,修改窗体显示
							try{											//然后将用户选择的数据回写到窗体上	
								this.updateDataDict.load(this.getSelected());
							}catch(err){
								Ext.Msg.alert('提示',err.description);
								this.updateDataDict.close();
							}
						},
						scope:this
					},"-",{
						text:'删除',
						icon:'../imgs/delete.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
						hidden :id == id.replace(c) ? false : true,
// 						handler:function(){
// 							this.onRemove
// 							Ext.Msg.confirm('提示','是否删除？',this.onRemove,this);
// 						},
						handler:function(){
							this.onRemove()	
						},
						scope:this
					}]
				})
				UserDataDictGrid.superclass.constructor.call(this,{
					id:'dataDictGrid',
					title:'用户数据字典列表',
					renderTo:'dataDictGrid',
					height:600,
					autoExpandColumn:4,
					//height : Ext.get('dataDictGrid').getHeight(), 
					sm:new Ext.grid.RowSelectionModel({
						singleSelect:true
					}),
					tbar:this.toolBar,
					bbar:new Ext.PagingToolbar({
						pageSize:20,
						store:this.store,
						displayInfo:true,
						displayMsg:'第{0}条到{1}条，共{2}条',
						emptyMsg:'没有记录'
					}),
					columns:[
					         //new Ext.grid.RowNumberer(),//自动行号
								{
									header:'名称',
									width:200,
									dataIndex:'dictName',
									sortable:true
								},{
									header:'附加值1',
									width:200,
									dataIndex:'value1',
									sortable:true
								},{
									header:'附加值2',
									width:200,
									dataIndex:'value2',
									sortable:true
								},{
									header:'父节点',
									width:200,
									dataIndex:'parentId',
									sortable:true
								},{
									header:'备注',
									dataIndex:'remark',
									sortable:true
								}]
				});
				this.getStore().load({
					url:'finddatas.action',
					params:{start:0,limit:20}
				});
				//this.insertDataDict.on('submit',this.onsubmit,this);		//为可视化窗口:insertWin添加事件(事件名称，调用的函数，scope)
			Ext.Ajax.on('requestcomplete',this.requestFunction,this);
		},
		//判断用户是否选择了数据
		getSelected:function(){
			var sm = this.getSelectionModel();
			if(sm.getCount() == 0){
				throw Error('需要选择一条数据');
			}
			return sm.getSelected();	
			
		},
		//删除数据
		onRemove:function(){
			var sm = this.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Msg.alert('提示','需要选择一条数据');
			}else{
				Ext.Msg.confirm('提示','是否删除？',function(btn, text){
					//Ext.Msg.confirm('提示','是否删除？',this.onRemove,this);
					if(btn == 'yes'){
						try{
							var store = this.store;
							var selectRe = this.getSelected();			//获得Grid选择的record
							
							store.remove(selectRe);
							
							Ext.Ajax.request({
								url:'deldatadic.action',
								params:{
									'dataDict.id':selectRe.get('id')
								},
								success : function(response){
									//alert(response.responseText);
									store.load({
											params:{start:0,limit:20}
										});
								}  
								
							});	//修改时，form联动
						}catch(err){
							Ext.Msg.alert('提示','需要选择一条数据');
						}
						//删除后,直接刷新
						
					}
				},this);
			}
		},
		insert:function(re){
			alert(11111);
			//alert(this.title);
			//此处的this为GridPanel
			this.getStore().add(re);	
		},
		update:function(re){
			try{
				var selectRe = this.getSelected();			//获得Grid选择的record
				var data = selectRe.data;
				//alert(Ext.util.JSON.encode(data));		//获得Record的数据，然后转换成JSON打印
				//遍历record.data,修改原record的值
				for(var i in data){
					//alert(i);
					selectRe.set(i,re.get(i));
					
				}
				selectRe.commit();
				this.fireEvent("rowselect", selectRe);		//修改时，form联动
				
			}catch(err){
				throw Error('需要选择一条数据');
			}
		},
		//在插入数据的时候,返回的ID需要重新加载到insertdata对象中,这样就同数据库一样了,根据ID可以修改和删除数据
		requestFunction:function(conn,response,options){
// 			var c = Ext.util.JSON.decode(response.responseText);
// 			alert(response.responseText)
// 			var res = c.list;
// 			for(var i = 0;i<res.length;i++){
// 				var rc = res[i];
// 			}
		}
		});
		new UserDataDictGrid();
	});
</script>
<title>数据字典列表</title>
</head>
<body>
<div id="dataDictGrid"  style="width:100%; height:100%" ></div>
</body>
</html>